import json
import os

#JSON配置文件
config_name = 'config.json'
config_path = os.path.join(os.path.dirname(__file__), config_name)

def read_interval_from_config():
    if os.path.exists(config_path):
        try:
            with open(config_path, 'r') as f:
                config = json.load(f)
        except Exception as e:
            return False
        interval = config['interval']
    else:
        interval = 300
    return interval
            
def read_headers_from_config():
    config_paths = [
        config_path,
        os.path.join(os.getcwd(), config_name),
    ]
     # 去重保持顺序
    seen = set()
    unique_paths = [p for p in config_paths if not (p in seen or seen.add(p))]
    config = None
    for p in unique_paths:
        try:
            if os.path.exists(p):
                with open(p, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                break
        except Exception as e:
            print(f"Failed to load config: {e}")

    headers = []
    if isinstance(config, dict):
        # 兼容大小写两种写法
        header_obj = config.get('header') or config.get('Header')
        if isinstance(header_obj, dict):
            try:
                # 先数字键（按数值排序），再非数字键（按字典序）
                numeric_keys = []
                string_keys = []
                for k in header_obj.keys():
                    try:
                        numeric_keys.append((int(k), k))
                    except Exception:
                        string_keys.append(k)
                ordered_keys = [k for _, k in sorted(numeric_keys)] + sorted(string_keys)

                for key in ordered_keys:
                    section = header_obj.get(key) or {}
                    val1 = section.get('param_1')
                    if isinstance(val1, str) and val1.strip():
                        headers.append(val1.strip())
                    val2 = section.get('param_2')
                    if isinstance(val2, str) and val2.strip():
                        headers.append(val2.strip())
            except Exception as e:
                print(f"Failed to parse header from config: {e}")

    if not headers:
        headers = [
            '1','2','3','4','5','6','7','8','9','10','11','12','13'
        ]
    return tuple(headers)

def write_interval_to_config(interval:int):
    try:
        with open(config_path, 'r') as f:
            config = json.load(f) 
    except Exception as e:
        print("Failed to read config:", e)
        config = None
        return False

    config['interval'] = interval
    try:
        with open(config_path, 'w') as f:
            json.dump(config, f)
    except Exception as e:
        return False
    return True

def write_headers_to_config(headers:dict):
    try:
        with open(config_path, 'r') as f:
            config = json.load(f)
    except Exception as e:
        print("Failed to read config:", e)
        config = None

    config['header'] = headers
    try:
        with open(config_path, 'w') as f:
            json.dump(config, f)
    except Exception as e:
        print("Failed to write config:", e)
